package com.shouhuobao.take;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.home.update.Update;
import com.iseastar.dianxiaosan.home.update.UpgradeBean;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.ForeService;
import com.iseastar.guojiang.app.WebViewActivity;
import com.iseastar.guojiang.loc.BaiduLocationService;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.login.LoginChooseActivity;
import com.shouhuobao.station.R;
import com.shouhuobao.take.home.HomeFragment;
import com.shouhuobao.take.mine.MyFragment;
import com.shouhuobao.take.model.BannerBean;

import droid.frame.activity.ActivityMgr;
import droid.frame.utils.android.Alert;
import droid.frame.utils.android.Log;
import droid.frame.utils.android.SharedPref;
import droid.frame.utils.http.MsgID;
import droid.frame.view.ViewPagerExt;

/**
 * 裹儿联盟主页
 *
 * @author coffee<br>
 * 2017年6月2日下午6:15:12
 */
public class MainActivity extends BaseActivity2 implements OnClickListener, OnPageChangeListener {

    private ViewPagerExt mViewPager;
    // 代收、代寄、我的
    private Fragment[] mFragments;

    private TextView[] mTabs = new TextView[3];
    private String mCurrentCity = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent service = new Intent();
        service.setClass(getContext(), ForeService.class);
        startService(service);
        //百度定位
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.putExtra("msgId", com.iseastar.guojiang.consts.MsgID.location_baidu);
        startService(intent);
        // 崩溃日志上传
        AppHttp.getInstance().crashUpload();
        // 检查版本升级
        AppHttp.getInstance().takeAppUpgrade(null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 检查是否登录
        boolean isLogin = AppLogic.checkLogin(getContext());
        if (isLogin == false) {
            startActivity(new Intent(getContext(), LoginChooseActivity.class));
            finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.take_main);
        super.findViewById();
        mViewPager = (ViewPagerExt) findViewById(R.id.viewpager);
        mViewPager.addOnPageChangeListener(this);
        // 订单列表--上门
        mFragments = new Fragment[3];
        mFragments[0] = new HomeFragment();
        mFragments[1] = new com.iseastar.dianxiaosan.home.HomeFragment();
        mFragments[2] = new MyFragment();
        mViewPager.setFragmentItems(getSupportFragmentManager(), mFragments);
        mViewPager.setOffscreenPageLimit(mTabs.length);

        mTabs[0] = (TextView) findViewById(R.id.main_tab_1);
        mTabs[1] = (TextView) findViewById(R.id.main_tab_2);
        mTabs[2] = (TextView) findViewById(R.id.main_tab_3);
        mTabs[0].setOnClickListener(this);
        mTabs[1].setOnClickListener(this);
        mTabs[2].setOnClickListener(this);

        boolean isOpenStation = getIntent().getBooleanExtra("isOpenStation", true);
        if (SharedPref.isFirstOpen(AppCache.getUser().getPhone()) && isOpenStation && null == AppCache.getUser().getStationId()) {
            Intent intent = new Intent(getContext(), WebViewActivity.class);
            intent.putExtra("title", "驿站开通");
            startActivity(intent);
        }
        SharedPref.setFirstOpen(AppCache.getUser().getPhone(), false);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_tab_1:
                mViewPager.setCurrentItem(0);
                setTabBackground(v);
                break;
            case R.id.main_tab_2:
                mViewPager.setCurrentItem(1);
                setTabBackground(v);
                break;
            case R.id.main_tab_3:
                mViewPager.setCurrentItem(2);
                setTabBackground(v);
                break;
            default:
                break;
        }
    }

    private void setTabBackground(View v) {
        if (mTabs[0].getId() == v.getId()) {
            mTabs[0].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_take, 0, 0);
            mTabs[1].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_send2, 0, 0);
            mTabs[2].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_mine2, 0, 0);
            mTabs[0].setTextColor(getResources().getColor(R.color.app_title_bg));
            mTabs[1].setTextColor(getResources().getColor(R.color.app_font_white));
            mTabs[2].setTextColor(getResources().getColor(R.color.app_font_white));

        } else if (mTabs[1].getId() == v.getId()) {
            mTabs[0].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_take2, 0, 0);
            mTabs[1].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_send, 0, 0);
            mTabs[2].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_mine2, 0, 0);
            mTabs[0].setTextColor(getResources().getColor(R.color.app_font_white));
            mTabs[1].setTextColor(getResources().getColor(R.color.app_title_bg));
            mTabs[2].setTextColor(getResources().getColor(R.color.app_font_white));

        } else if (mTabs[2].getId() == v.getId()) {
            mTabs[0].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_take2, 0, 0);
            mTabs[1].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_send2, 0, 0);
            mTabs[2].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_mine, 0, 0);
            mTabs[0].setTextColor(getResources().getColor(R.color.app_font_white));
            mTabs[1].setTextColor(getResources().getColor(R.color.app_font_white));
            mTabs[2].setTextColor(getResources().getColor(R.color.app_title_bg));
        }
    }

    @Override
    public void onPageSelected(int index) {
        if (mFragments != null) {
            setTabBackground(mTabs[index]);
//            mFragments[index].onResume();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    /**
     * 暂停营业的时候禁止viewpager滑动和点击
     */
    public void stopSlideClick() {
        // mTabs[0].setClickable(false);
        // mTabs[1].setClickable(false);
        // mViewPager.setSupportScroll(false);
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 版本更新
            case com.iseastar.guojiang.consts.MsgID.station_update:
                final ReqResult<UpgradeBean> result = JSON.parser(msg.obj, UpgradeBean.class);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UpgradeBean item = result.getResult();
                            if (item != null) {
                                if (item.getIsNeedUpdate() == 1 || item.getIsNeedUpdate() == 2) {
                                    Update update = new Update(ActivityMgr.peek());
                                    update.doNewVersionUpdate(item.getDownloadUrl(), item.getDescription(), item.getIsNeedUpdate());
                                }
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return false;
            //            case MsgID.take_getuser_info:
            //                final ReqResult<UserBean> reqResult = JSON.parser(msg.obj, UserBean.class);
            //                runOnUiThread(new Runnable() {
            //                    @Override
            //                    public void run() {
            //                        if (reqResult.isSuccess()) {
            //                            UserBean user = reqResult.getResult();
            //                            if (isEmpty(user.getPhone())) {
            //                                user.setPhone(AppCache.getUser().getPhone());
            //                            }
            //                            AppCache.setUser(user);
            //                        }
            //                    }
            //                });
            //                return false;
            case MsgID.net_unavailable:
                showToast(msg.obj.toString());
                return false;
            // 获取百度定位
            case com.iseastar.guojiang.consts.MsgID.location_baidu:
                BDLocation loc = (BDLocation) msg.obj;
                if (loc == null) {
                    mCurrentCity = "北京市";
                    return false;
                } else {
                    mCurrentCity = loc.getCity();
                    if (isEmpty(mCurrentCity)) {
                        mCurrentCity = "北京市";
                    }
                }
                AppHttp.getInstance().getBannerData(mCurrentCity);
                return false;
            //banner数据
            case com.iseastar.guojiang.consts.MsgID.take_get_banner_data:
                final ReqResult<BannerBean> result1 = JSON.parseList(msg.obj, BannerBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result1)) {
                            ((HomeFragment) mFragments[0]).setBannerData(result1.getResultList());
                        } else {
                            showToast(result1.getMessage());
                        }
                    }
                });

                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private int backCount;
    private final long DELAY_BACK = 2000;
    private final int MSG_BACK = 1000;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_BACK:
                    backCount = 0;
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
                    // 如果for循环执行完, 所有的FrameBaseFragment均不是toBackStack 则拦截back键盘
                    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() != KeyEvent.ACTION_UP) {
                        backCount++;
                        Log.d("onBackPressed", backCount);
                        if (backCount == 2) {
                            ActivityMgr.finishAll();
                        } else {
                            // Alert.toastByView("再按一次返回键退出", Toast.LENGTH_SHORT).show();
                            Alert.toast("再按一次返回键退出");
                            mHandler.sendEmptyMessageDelayed(MSG_BACK, DELAY_BACK);
                        }
                        return true;
                    }
                }
                return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }
}
